package com.wutianyi.datanucleus.main;

import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;

import com.wutianyi.datanucleus.dataobject.Inventory;
import com.wutianyi.datanucleus.dataobject.Product;

public class Main {
	public static void main(String[] args) {
		PersistenceManagerFactory pmf = JDOHelper
				.getPersistenceManagerFactory("datanucleus.properties");
		PersistenceManager pm = pmf.getPersistenceManager();

		Transaction tx = pm.currentTransaction();
		try {
			tx.begin();
			Inventory inv = new Inventory("My Inventory2");
			Product product = new Product("Sony Discman",
					"A standard discman from Sony", 49.99);
			inv.getProducts().add(product);
			pm.makePersistent(inv);
			tx.commit();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			pm.close();
		}
		pm = pmf.getPersistenceManager();
		tx = pm.currentTransaction();
		try {
			tx.begin();
			Query q = pm.newQuery("select from products"
					+ "where price < 150.00 order by price asc");
			List<Product> products = (List<Product>) q.execute();
			for (Product p : products) {
				System.out.println(p.getId() + " : " + p.getName() + " : "
						+ p.getDescription() + " : " + p.getPrice());
			}
			tx.commit();

		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			pm.close();
		}

	}
}
